﻿using System;
using System.Collections.Generic;
using System.Data;
using MedicService.Domain;

namespace MedicService.Server.Factory {
    public class ObjectNameFactory {

        readonly protected string TableName = "ObjectName";

        protected Dictionary<String, ObjectNameEntity> ItemsMap;

        public void InitMap() {
            ItemsMap = GetMap();
        }

        public Dictionary<string, ObjectNameEntity> GetMap() {
            var entities = new Dictionary<string, ObjectNameEntity>();
            var dataTable = DatabaseConnector.GetData(TableName, "object");
            foreach (DataRow myDataRow in dataTable.Rows) {
                var entity = new ObjectNameEntity();
                FillEntity(entity, myDataRow);
                entities.Add(entity.Object, entity);
            }
            return entities;
        }

        public virtual void Save(ObjectNameEntity entity) {
            var dataTable = DatabaseConnector.GetData(TableName, "object", "object='" + entity.Object + "'");
            var rows = dataTable.Rows;
            if (rows.Count > 0) {
                var query = GetUpdateQuery(entity);
                DatabaseConnector.Update(query);
            }else {
                var query = GetInsertQuery(entity);
                DatabaseConnector.Insert(query);
            }
        }

        protected string GetInsertQuery(ObjectNameEntity entity) {
            string s = "INSERT INTO [ObjectName]"
                       + "           ([object]"
                       + "           ,[name])"
                       + "     VALUES"
                       + "           (" + Nullable(entity.Object)
                       + "           ," + Nullable(entity.Name) + ");"
                       + "     SELECT 0";
            return s;
        }

        protected string GetUpdateQuery(ObjectNameEntity entity) {
            string s = "UPDATE [ObjectName]"
                       + "   SET [name] = "+Nullable(entity.Name)
                       + " WHERE object='" + entity.Object + "'";
            return s;
        }

        protected void FillEntity(ObjectNameEntity entity, DataRow myDataRow) {
            entity.Name = myDataRow["name"] as string;
            entity.Object = myDataRow["object"] as string;
            if (string.IsNullOrEmpty(entity.Name)) {
                entity.Name = entity.Object;
            }
        }

        protected static string Nullable(object o) {
            if (o == null) {
                return "NULL";
            } else {
                string s = "" + o;
                if (string.IsNullOrEmpty(s)) {
                    return "NULL";
                } else {
                    return "'" + s + "'";
                }
            }
        }

    }
}